<?php
use Workerman\Worker;
require_once __DIR__ . '/Workerman/Autoloader.php';

// 注意：这里与上个例子不同，使用的是websocket协议
$ws_worker = new Worker("websocket://0.0.0.0:9680");

// 启动4个进程对外提供服务
$ws_worker->count = 4;

$global_uid = 0;

$ws_worker->onConnect = function($connection)
{
    global $ws_worker, $global_uid;
    // 为这个连接分配一个uid
    $connection->uid = ++$global_uid;
    $data = [
        "type"=>"connect",
        "connect_num" => $connection->uid,
        "data" => ['ip' => $connection->getRemoteIp(),'id' => $connection->id]
    ];
    foreach($ws_worker->connections as $conn)
    {
        $conn->send(json_encode($data));
    }
};

// 当收到客户端发来的数据后返回hello $data给客户端
$ws_worker->onMessage = function($connection, $data)
{
    // 向客户端发送hello $data
//    $connection->send('hello ' . $data);
    $connection->send($connection->ip.','. $data);
};

// 运行worker
Worker::runAll();